package main

import (
	"flag"
	"fmt"
	"log"
	"time"

	"github.com/apache/iotdb-client-go/client"
)

func main() {
	// 定义命令行参数
	host := flag.String("host", "localhost", "IoTDB 服务器的主机名")
	port := flag.String("port", "6667", "IoTDB 服务器的端口号")
	username := flag.String("username", "root", "IoTDB 的用户名")
	password := flag.String("password", "root", "IoTDB 的密码")
	storageGroup := flag.String("storage-group", "root.ln.test.*", "要清理的存储组")
	days := flag.Int("days", 30, "清理多久之前的数据(天)")
	flag.Parse()

	// 计算时间戳
	deleteTime := time.Now().AddDate(0, 0, -(*days)).Format("2006-01-02T15:04:05")

	// 配置 SessionPool
	config := &client.PoolConfig{
		Host:     *host,
		Port:     *port,
		UserName: *username,
		Password: *password,
	}

	// 创建 SessionPool
	sessionPool := client.NewSessionPool(config, 3, 60000, 60000, false)

	defer sessionPool.Close()

	// 从 SessionPool 获取一个 Session
	session, err := sessionPool.GetSession()
	if err != nil {
		log.Fatalf("无法从 SessionPool 获取 Session: %v", err)
	}
	defer sessionPool.PutBack(session)

	// 构建删除语句
	deleteStmt := fmt.Sprintf("DELETE FROM %s WHERE time < %s", *storageGroup, deleteTime)

	// 执行删除语句
	log.Printf("执行删除语句 %s\n", deleteStmt)
	_, err = session.ExecuteNonQueryStatement(deleteStmt)
	if err != nil {
		log.Fatalf("执行删除语句时出错: %v", err)
	}

	log.Printf("成功删除 %s 中 %d 天之前的旧数据\n", *storageGroup, *days)
}
